package com.mmall.Concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

@Slf4j
public class CyclicBarrierExample2 {
    private static CyclicBarrier barrier = new CyclicBarrier(5);

    public static void main(String[] args) throws Exception {
        ExecutorService executorService = Executors.newCachedThreadPool();
        for (int i = 0; i < 10; i++) {
            final int num = i;
           Thread.sleep(1000);
            executorService.execute(()->{
                try{
                    race(num);
                }catch (Exception e){
                    log.info("exception",e);
                }
            });
        }
        executorService.shutdown();
    }

    public static void race(int threadNum) throws Exception{
        log.info("{} is ready",threadNum);
        try{
            barrier.await(2, TimeUnit.SECONDS);
        }catch (BrokenBarrierException|TimeoutException |InterruptedException e){
            log.warn("Exception",e);
        }

        log.info("{} continue",threadNum);

    }
}
